<template>
  <BasicModal v-bind="$attrs" @register="registerModal" destroyOnClose :title="title" :width="1024" @ok="handleSubmit">
    <BasicForm @register="registerForm" ref="formRef">
      <template #billTypeSlot="{ model, field }">
        <a-input-search v-model:value="model[field]" :disabled="isDetail" readonly placeholder="请选择单据类型" @search="billTypeOpen" />
      </template>
      <!-- <template #currencySlot="{ model, field }">
        <a-input-search v-model:value="model[field]" :disabled="isDetail" readonly placeholder="请选择币种" @search="open" />
      </template> -->
      <!-- <template #organizationSlot="{ model, field }">
        <a-input-search v-model:value="model[field]" :disabled="isDetail" readonly placeholder="请选择组织" @search="openOrganization" />
      </template> -->
      <template #supplierSlot="{ model, field }">
        <a-input-search v-model:value="model[field]" placeholder="请选择供应商" :disabled="isDetail" readonly @search="openSupplier('master')" />
      </template>
    </BasicForm>
    <!-- 子表单区域 -->
    <a-tabs v-model:activeKey="activeKey" animated @change="handleChangeTabs">
      <a-tab-pane tab="请购行信息" key="busBuyingRequisitionItem" :forceRender="true">
        <JVxeTable
          keep-source
          resizable
          ref="busBuyingRequisitionRef"
          :loading="busBuyingRequisitionItemTable.loading"
          :columns="busBuyingRequisitionItemTable.columns"
          :dataSource="busBuyingRequisitionItemTable.dataSource"
          :height="340"
          :rowNum="true"
          rowNumKey="rowNum"
          :rowSelection="true"
          @added="added"
          :disabled="formDisabled"
          :toolbar="true"
        >
          <template #action="props">
            <a-input-search @click="handleView(props)" placeholder="请选择料品编码" readonly v-model:value="props.row.materialCode"></a-input-search>
          </template>
          <template #organizationSlot="props">
            <a-input
              @click="organizationHandleView(props)"
              placeholder="请选择业务组织名称"
              v-model:value="props.row.organizationName"
            ></a-input>
          </template>
          <template #supplierSlot="props">
            <a-input-search v-model:value="props.row.supplierName" placeholder="请选择供应商" :disabled="isDetail" readonly @search="openSupplier('sublist',props)" />
          </template>
        </JVxeTable>
      </a-tab-pane>
      
      <a-tab-pane tab="采购信息" key="purchasingInformation" :forceRender="true" v-if="isDetail">
        <JVxeTable
          keep-source
          resizable
          ref="purchasingInformation"
          :loading="purchasingInformationTable.loading"
          :columns="purchasingInformationTable.columns"
          :dataSource="purchasingInformationTable.dataSource"
          :height="340"
          :rowNumber="true"
          :disabled="formDisabled"
        >
        </JVxeTable>
      </a-tab-pane>
    </a-tabs>
  </BasicModal>
  <!-- 单据类型 -->
  <billTypeSelectModel @register="billTypeRegModal" @getSelectResult="billTypehandleSuccess" v-bind="getBindValue"></billTypeSelectModel>
  <!-- 币种 -->
  <currencySelectModel @register="regModal" @getSelectResult="handleSuccess" v-bind="getBindValue"></currencySelectModel>
  <!-- 接单组织 -->
  <organizationSelectModel
    @register="organizationRegModal"
    @getSelectResult="organizationHandleSuccess"
    v-bind="getBindValue"
  ></organizationSelectModel>
  <!-- 料品 -->
  <materialSelectModel @register="materialRegModal" @getSelectResult="materialhandleSuccess" v-bind="getBindValue"></materialSelectModel> 
  <!-- 供应商 -->
  <supplierSelectModel @register="supplierRegModal" @getSelectResult="supplierHandleSuccess" v-bind="getBindValue"></supplierSelectModel>
  
</template>

<script lang="ts" setup>
import { ref, computed, unref, reactive } from 'vue';
import { BasicModal, useModalInner, useModal } from '/@/components/Modal';
import { BasicForm, useForm } from '/@/components/Form/index';
import { JVxeTable } from '/@/components/jeecg/JVxeTable';
import { useJvxeMethod } from '/@/hooks/system/useJvxeMethods.ts';
import { formSchema, busBuyingRequisitionItemColumns,busBuyingRequisitionPurchaseColumns } from '../BusBuyingRequisition.data';
import { saveOrUpdate,busBuyingRequisitionItemList,busBuyingRequisitionPurchaseList} from '../BusBuyingRequisition.api';
import { VALIDATE_FAILED } from '/@/utils/common/vxeUtils';
import billTypeSelectModel from '/@/views/components/billTypeSelectModel.vue';
import currencySelectModel from './currencySelectModel.vue';
import organizationSelectModel from './organizationSelectModel.vue';
import materialSelectModel from './materialSelectModel.vue';
import supplierSelectModel from '/@/views/components/supplierSelectModel.vue';
import {localStorage} from '/@/utils/store/locaStore';
import { queryUserOrganization } from '/@/views/system/depart/depart.api';
// Emits声明
const emit = defineEmits(['register', 'success']);
const isUpdate = ref(true);
const isDetail = ref(false);
const formDisabled = ref(false);
// 供应商标识
let supplierFlag = ref(null);

const refKeys = ref(['busBuyingRequisitionRef']);
const activeKey = ref('busBuyingRequisitionItem');
const busBuyingRequisitionRef = ref();
const tableRefs = { busBuyingRequisitionRef };
const busBuyingRequisitionItemTable = reactive({
  loading: false,
  dataSource: [],
  columns: busBuyingRequisitionItemColumns,
});
const purchasingInformationTable = reactive({
  loading: false,
  dataSource: [],
  columns: busBuyingRequisitionPurchaseColumns,
});
//表单配置
const [registerForm, { setProps, resetFields, setFieldsValue,getFieldsValue, validate }] = useForm({
  labelWidth: 120,
  schemas: formSchema,
  showActionButtonGroup: false,
  baseColProps: { span: 8 },
});
//表单赋值
const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
  //重置表单
  await reset();
  // 获取用户当前组织
  getCurrentDeparts();
  setModalProps({ confirmLoading: false, showCancelBtn: data?.showFooter, showOkBtn: data?.showFooter });
  isUpdate.value = !!data?.isUpdate;
  isDetail.value = !!data?.isDetail;
  formDisabled.value = !data?.showFooter;
  if (unref(isUpdate)) {
    //表单赋值
    await setFieldsValue({
      ...data.record,
    });
    requestSubTableData(busBuyingRequisitionItemList, { id: data?.record?.id }, busBuyingRequisitionItemTable);
  }
  
  if(unref(isDetail)) {
    requestSubTableData(busBuyingRequisitionPurchaseList, { id: data?.record?.id }, purchasingInformationTable);
  }
  // 隐藏底部时禁用整个表单
  setProps({ disabled: !data?.showFooter });
});
//方法配置
const [handleChangeTabs, handleSubmit, requestSubTableData, formRef] = useJvxeMethod(
  requestAddOrEdit,
  classifyIntoFormData,
  tableRefs,
  activeKey,
  refKeys
);

//设置标题
const title = computed(() => ( unref(isDetail) ? '详情' : !unref(isUpdate) ? '新增' : '编辑'));

async function reset() {
  await resetFields();
  activeKey.value = 'busBuyingRequisitionItem';
  busBuyingRequisitionItemTable.dataSource = [];
}
function classifyIntoFormData(allValues) {  
  let main = Object.assign({}, allValues.formValue);
  return {
    ...main, // 展开
    busBuyingRequisitionItemList: allValues.tablesValue[0].tableData,
  };
}

//表单提交事件
async function requestAddOrEdit(values) {
  try {
    setModalProps({ confirmLoading: true });
    //提交表单
    
    values.requisitionDepartmentName = localStorage.get('requisitionDepartmentId')
    values.requisitionPersonnelName = localStorage.get('requisitionPersonnelId')
    localStorage.remove('requisitionDepartmentId')
    localStorage.remove('requisitionPersonnelId')
    values.busBuyingRequisitionItemList.map(item => {
      delete item.id;
    });

    await saveOrUpdate(values, isUpdate.value);
    //关闭弹窗
    closeModal();
    //刷新列表
    emit('success');
  } finally {
    setModalProps({ confirmLoading: false });
  }
}
const [billTypeRegModal, { openModal: openBillTypeModal }] = useModal();
const [organizationRegModal, { openModal: openOrganizationModal }] = useModal();
const [materialRegModal, { openModal: openMaterialModal }] = useModal();
const [regModal, { openModal }] = useModal();
const [unitRegModal, { openModal: openUnitModal }] = useModal();
const [supplierRegModal, { openModal: supplierModal }] = useModal();

//单据类型
function billTypeOpen() {
  openBillTypeModal(true, {
    isUpdate: false,
    showFooter: true,
    tableName:"bus_buying_requisition"
  });
}
//打开选择币种
function open() {
  openModal(true, {
    isUpdate: false,
    showFooter: true,
  });
}
async function getCurrentDeparts() {
  const result = await queryUserOrganization({});
  result.list.forEach(item => {
    if(result.organizationId == item.id) {
      setFieldsValue({
        organizationId: item.id,
        organizationName: item.organizationName,
      });
    }
  });
}
// 点击新增时，如果主表选择了供应商  子表自动带上供应商
function added({row,rows}) {
  
  let currentMasterData = getFieldsValue();
  if(currentMasterData.organizationId) {
    let tempArr = [
      {
      rowKey : row.id,
      values:{
        supplierName : currentMasterData.supplierName,
        supplierId : currentMasterData.supplierId
      }
    }];
    busBuyingRequisitionRef.value!.setValues(tempArr)
  }
}
//打开选择供应商
function openSupplier(flag,props) {
  supplierFlag = flag;
  index = props?.params.$rowIndex;
  
  supplierModal(true, {
    isUpdate: false,
    showFooter: true
  });
}
//打开选择销售组织
function openOrganization() {
  openOrganizationModal(true, {
    isUpdate: false,
    showFooter: true,
  });
}
let index: number | null = null;
//打开选择料品
function handleView(props) {
  index = props.params.$rowIndex;
  openMaterialModal(true, {
    isUpdate: false,
    showFooter: true,
  });
}
//打开业务组织
function organizationHandleView(props) {
  index = props.params.$rowIndex;
  openOrganizationModal(true, {
    isUpdate: false,
    showFooter: true,
  });
}
//打开选择单位
function unitHandleView(props) {
  index = props.params.$rowIndex;
  openUnitModal(true, {
    isUpdate: false,
    showFooter: true,
  });
}
const getBindValue = Object.assign({}, '');
//供应商回写
function supplierHandleSuccess(val, values) {
  if(supplierFlag == 'master') {
    setFieldsValue({
      supplierName : val[0].label,
      supplierId: val[0].value,
    });
  } else {
    busBuyingRequisitionItemTable.dataSource = busBuyingRequisitionRef.value!.getTableData();
    busBuyingRequisitionItemTable.dataSource[index].supplierName = val[0].label;
    busBuyingRequisitionItemTable.dataSource[index].supplierId = val[0].value;
  }
}
//单据类型回写
function billTypehandleSuccess(val, values) {
  setFieldsValue({
    billTypeName: val[0].label,
    billTypeId: val[0].value,
  });
}
//币种选择回写
function handleSuccess(val, values) {
  setFieldsValue({
    currencyName: val[0].label,
    currencyId: val[0].value,
  });
}
//组织回写
function organizationHandleSuccess(val, values) {
  setFieldsValue({
    organizationName: val[0].label,
    organizationId: val[0].value,
  });
  if (index != null) {
    busBuyingRequisitionItemTable.dataSource = busBuyingRequisitionRef.value!.getTableData();
    busBuyingRequisitionItemTable.dataSource[index].organizationName = val[0].label;
    busBuyingRequisitionItemTable.dataSource[index].organizationId = val[0].value;

  }
}
//料品回写
function materialhandleSuccess(val, values) {
  busBuyingRequisitionItemTable.dataSource = busBuyingRequisitionRef.value!.getTableData();
  busBuyingRequisitionItemTable.dataSource[index].materialName = val[0].label;
  busBuyingRequisitionItemTable.dataSource[index].materialId = val[0].value;  
  busBuyingRequisitionItemTable.dataSource[index].materialCode = val[0].item.code;
  busBuyingRequisitionItemTable.dataSource[index].specifications = val[0].item.spec;
  // 自动带出单位
  busBuyingRequisitionItemTable.dataSource[index].unitId = val[0].item.stockUnitId;
  busBuyingRequisitionItemTable.dataSource[index].unitName = val[0].item.stockUnitName;
}
//单位回写
function unithandleSuccess(val, values) {
  busBuyingRequisitionItemTable.dataSource = busBuyingRequisitionRef.value!.getTableData();
  busBuyingRequisitionItemTable.dataSource[index].unitName = val[0].label;
  busBuyingRequisitionItemTable.dataSource[index].unitId = val[0].value;
}
</script>

<style lang="less" scoped>
/** 时间和数字输入框样式 */
:deep(.ant-input-number) {
  width: 100%;
}

:deep(.ant-calendar-picker) {
  width: 100%;
}
</style>